package br.com.checkandgo;

import br.com.checkandgo.model.Constants;
import br.com.checkandgo.model.PontosRota;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.parse.ParseObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity implements LocationListener{

	public LatLng START_LOCATION = new LatLng(0, 0);
	public LatLng CURRENT_LOCATION = new LatLng(0, 0);
	private GoogleMap map;
	public LocationManager locationManager;
	public Marker start;
	public Marker current;
	public boolean isFirst = true;
	public static PontosRota pontos = new PontosRota();

	public ToggleButton button;
	public Button button2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_fragment);

		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		button = (ToggleButton) findViewById(R.id.button1);
		button2 = (Button) findViewById(R.id.button2);

		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(button.isChecked()) {
					initMap();
				} else {
					locationManager.removeUpdates(MainActivity.this);
					Intent intent = new Intent(MainActivity.this, RouteActivity.class);
					Constants.setPontosRota(pontos);
					startActivity(intent);

				}
			}
		});

		button2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Location currentLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(new Criteria(), false));
				LatLng loc = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
				pontos.addPoint(loc);
				locationManager.removeUpdates(MainActivity.this);
				Intent intent = new Intent(MainActivity.this, RouteActivity.class);
				Constants.setPontosRota(pontos);
				startActivity(intent);

			}
		});

	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.conta, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			Intent intent = new Intent(MainActivity.this, ContaActivity.class);
			startActivity(intent);
			return true;
		}
		if (id == R.id.home) {
			Intent intent = new Intent(MainActivity.this, MenuPrincipalActivity.class);
			startActivity(intent);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void initMap() {
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, this);

		if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
			Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
			startActivity(intent);
		}

		loadMap();
		pontos.addPoint(CURRENT_LOCATION);

	}

	public void loadMap() {
		Location currentLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(new Criteria(), false));
		START_LOCATION = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
		CURRENT_LOCATION = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());

		map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
		start = map.addMarker(new MarkerOptions().position(START_LOCATION).title("Localizacao Inicial"));

		current = map.addMarker(new MarkerOptions()
		.position(new LatLng(CURRENT_LOCATION.latitude , CURRENT_LOCATION.longitude))
		.title("Atual")
		.snippet("Localizacao Atual"));

		// Move the camera instantly to hamburg with a zoom of 15.
		map.moveCamera(CameraUpdateFactory.newLatLngZoom(START_LOCATION, 19));

		// Zoom in, animating the camera.
		map.animateCamera(CameraUpdateFactory.zoomTo(17), 2000, null);
	}


	@Override
	public void onLocationChanged(Location location) {
		CURRENT_LOCATION = new LatLng(location.getLatitude(), location.getLongitude());
		current.setPosition(CURRENT_LOCATION);
		LatLng lastPos = pontos.getPoints().get(pontos.getPoints().size()-1);



		if(distFrom(lastPos.latitude, lastPos.longitude, CURRENT_LOCATION.latitude, CURRENT_LOCATION.longitude)) {
			if (isFirst) {
				start.setPosition(CURRENT_LOCATION);
				pontos.getPoints().remove(0);
				isFirst = false;
			}
			drawRoute();
		}
		isFirst = false;
	}

	public void drawRoute() {
		pontos.addPoint(CURRENT_LOCATION);
		PolylineOptions options = new PolylineOptions().width(4).color(Color.RED).visible(true);

		for (LatLng latlng : pontos.getPoints()) {
			options.add(latlng);
		}

		map.addPolyline(options);
		//		new RotaAsyncTask(this, map, this, rota).execute(lastPos.latitude,lastPos.longitude, CURRENT_LOCATION.latitude, CURRENT_LOCATION.longitude);
		Toast.makeText(MainActivity.this, "tamanho atual: "+pontos.getPoints().size(), Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	public boolean distFrom(double latitude, double longitude, double latitude2, double longitude2) {
		double earthRadius = 3958.75;
		double dLat = Math.toRadians(latitude2-latitude);
		double dLng = Math.toRadians(longitude2-longitude);
		double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
				Math.cos(Math.toRadians(latitude)) * Math.cos(Math.toRadians(latitude2)) *
				Math.sin(dLng/2) * Math.sin(dLng/2);
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		double dist = earthRadius * c;

		int meterConversion = 1609;

		float result = (float) (dist * meterConversion);
		if(result > 36){
			return true;
		} else {
			return false;
		}
	}

	@Override
	protected void onDestroy() {
		locationManager.removeUpdates(this);
		super.onDestroy();
	}

}